package rpc_netty.server.conf;

import org.omg.CORBA.PRIVATE_MEMBER;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.*;

//配置管理，读取properties文件中的配置，并添加到map集合中
//server在启动的过程中，通过该类获得配置
public class ConfigureMagment {

        private volatile static ConfigureMagment configureMagment;
        private static Logger logger= LoggerFactory.getLogger(ConfigureMagment.class);
        private static HashMap<String,String> data=new HashMap<>();

        //默认配置
        static {
            data.put("ServiceRegistryType","Nacos");
            data.put("ServiceRegistryUrl","localhost:8848");
            data.put("CurrentServiceUrl","localhost:8087");
            data.put("SerializerType","Json");
        }

        //dcl 单例设计模式
        public static ConfigureMagment getConfigureMagment(){
            if (configureMagment==null){
                synchronized (ConfigureMagment.class){
                    if (configureMagment==null){
                        configureMagment=new ConfigureMagment();
                    }
                }
            }
            return configureMagment;
        }

        //从配置文件中读取配置
        private ConfigureMagment(){
            try {
                FileInputStream fileInputStream=new FileInputStream("src/rpc_server.properties");
                Properties properties=new Properties();
                properties.load(fileInputStream);
                Set<Object> objects = properties.keySet();
                Iterator<Object> iterator = objects.iterator();
                while (iterator.hasNext()){
                    String key = (String)iterator.next();
                    data.put(key,properties.getProperty(key));
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        public String getProperty(String key){
            if (!data.containsKey(key)){
                logger.error("key does not exist");
                return null;
            }else
                return data.get(key);
        }
}
